import { ApiResponse, PaginatedData, SearchResult } from './types';
import { mockUsers, mockCampsites, mockPosts, mockComments, mockConversations, mockMessages } from './data';

// 模拟网络延迟
const delay = (ms: number = 500) => new Promise(resolve => setTimeout(resolve, ms));

// 模拟API响应包装器
const createResponse = <T>(data: T, message: string = 'success'): ApiResponse<T> => ({
  code: 200,
  message,
  data
});

// 模拟分页数据
const createPaginatedResponse = <T>(list: T[], page: number = 1, pageSize: number = 10): PaginatedData<T> => {
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  const paginatedList = list.slice(start, end);
  
  return {
    list: paginatedList,
    total: list.length,
    page,
    pageSize,
    hasMore: end < list.length
  };
};

// 用户相关API
export const userApi = {
  // 获取用户信息
  async getUserInfo(userId: string) {
    await delay();
    const user = mockUsers.find(u => u.id === userId);
    if (!user) {
      return { code: 404, message: '用户不存在', data: null };
    }
    return createResponse(user);
  },

  // 获取当前用户信息
  async getCurrentUser() {
    await delay();
    return createResponse(mockUsers[0]);
  },

  // 更新用户信息
  async updateUserInfo(userInfo: Partial<typeof mockUsers[0]>) {
    await delay();
    const updatedUser = { ...mockUsers[0], ...userInfo };
    return createResponse(updatedUser, '更新成功');
  },

  // 关注/取消关注用户
  async toggleFollow(userId: string) {
    await delay();
    const user = mockUsers.find(u => u.id === userId);
    if (user) {
      user.isFollowing = !user.isFollowing;
      user.followersCount += user.isFollowing ? 1 : -1;
    }
    return createResponse({ isFollowing: user?.isFollowing }, '操作成功');
  }
};

// 帖子相关API
export const postApi = {
  // 获取推荐帖子列表
  async getRecommendPosts(page: number = 1, pageSize: number = 10) {
    await delay();
    const paginatedData = createPaginatedResponse(mockPosts, page, pageSize);
    return createResponse(paginatedData);
  },

  // 获取关注用户的帖子
  async getFollowingPosts(page: number = 1, pageSize: number = 10) {
    await delay();
    // 模拟关注用户的帖子（这里简单返回部分数据）
    const followingPosts = mockPosts.slice(0, 2);
    const paginatedData = createPaginatedResponse(followingPosts, page, pageSize);
    return createResponse(paginatedData);
  },

  // 获取帖子详情
  async getPostDetail(postId: string) {
    await delay();
    const post = mockPosts.find(p => p.id === postId);
    if (!post) {
      return { code: 404, message: '帖子不存在', data: null };
    }
    return createResponse(post);
  },

  // 点赞/取消点赞
  async toggleLike(postId: string) {
    await delay();
    const post = mockPosts.find(p => p.id === postId);
    if (post) {
      post.isLiked = !post.isLiked;
      post.likesCount += post.isLiked ? 1 : -1;
    }
    return createResponse({ isLiked: post?.isLiked, likesCount: post?.likesCount }, '操作成功');
  },

  // 收藏/取消收藏
  async toggleCollect(postId: string) {
    await delay();
    const post = mockPosts.find(p => p.id === postId);
    if (post) {
      post.isCollected = !post.isCollected;
    }
    return createResponse({ isCollected: post?.isCollected }, '操作成功');
  },

  // 发布帖子
  async createPost(postData: any) {
    await delay();
    const newPost = {
      id: String(mockPosts.length + 1),
      ...postData,
      author: mockUsers[0],
      likesCount: 0,
      commentsCount: 0,
      sharesCount: 0,
      isLiked: false,
      isCollected: false,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
    mockPosts.unshift(newPost);
    return createResponse(newPost, '发布成功');
  }
};

// 营地相关API
export const campsiteApi = {
  // 获取营地列表
  async getCampsites(page: number = 1, pageSize: number = 10, filters?: any) {
    await delay();
    let filteredCampsites = [...mockCampsites];
    
    // 简单的筛选逻辑
    if (filters?.tags?.length) {
      filteredCampsites = filteredCampsites.filter(campsite => 
        filters.tags.some((tag: string) => campsite.tags.includes(tag))
      );
    }
    
    const paginatedData = createPaginatedResponse(filteredCampsites, page, pageSize);
    return createResponse(paginatedData);
  },

  // 获取营地详情
  async getCampsiteDetail(campsiteId: string) {
    await delay();
    const campsite = mockCampsites.find(c => c.id === campsiteId);
    if (!campsite) {
      return { code: 404, message: '营地不存在', data: null };
    }
    return createResponse(campsite);
  },

  // 搜索营地
  async searchCampsites(keyword: string, page: number = 1, pageSize: number = 10) {
    await delay();
    const filteredCampsites = mockCampsites.filter(campsite => 
      campsite.name.includes(keyword) || 
      campsite.description.includes(keyword) ||
      campsite.location.address.includes(keyword)
    );
    const paginatedData = createPaginatedResponse(filteredCampsites, page, pageSize);
    return createResponse(paginatedData);
  }
};

// 评论相关API
export const commentApi = {
  // 获取帖子评论
  async getPostComments(postId: string, page: number = 1, pageSize: number = 10) {
    await delay();
    const postComments = mockComments.filter(c => c.postId === postId);
    const paginatedData = createPaginatedResponse(postComments, page, pageSize);
    return createResponse(paginatedData);
  },

  // 发表评论
  async createComment(commentData: any) {
    await delay();
    const newComment = {
      id: String(mockComments.length + 1),
      ...commentData,
      author: mockUsers[0],
      likesCount: 0,
      isLiked: false,
      createdAt: new Date().toISOString()
    };
    mockComments.push(newComment);
    return createResponse(newComment, '评论成功');
  }
};

// 消息相关API
export const messageApi = {
  // 获取会话列表
  async getConversations() {
    await delay();
    return createResponse(mockConversations);
  },

  // 获取会话消息
  async getMessages(conversationId: string, page: number = 1, pageSize: number = 20) {
    await delay();
    const conversationMessages = mockMessages.filter(m => m.conversationId === conversationId);
    const paginatedData = createPaginatedResponse(conversationMessages, page, pageSize);
    return createResponse(paginatedData);
  },

  // 发送消息
  async sendMessage(messageData: any) {
    await delay();
    const newMessage = {
      id: String(mockMessages.length + 1),
      ...messageData,
      sender: mockUsers[0],
      isRead: false,
      createdAt: new Date().toISOString()
    };
    mockMessages.push(newMessage);
    return createResponse(newMessage, '发送成功');
  }
};

// 搜索相关API
export const searchApi = {
  // 综合搜索
  async search(keyword: string) {
    await delay();
    
    const posts = mockPosts.filter(post => 
      post.title.includes(keyword) || 
      post.content.includes(keyword) ||
      post.tags.some(tag => tag.includes(keyword))
    );
    
    const campsites = mockCampsites.filter(campsite => 
      campsite.name.includes(keyword) || 
      campsite.description.includes(keyword)
    );
    
    const users = mockUsers.filter(user => 
      user.nickname.includes(keyword) || 
      user.username.includes(keyword)
    );
    
    const searchResult: SearchResult = {
      posts: posts.slice(0, 10),
      campsites: campsites.slice(0, 10),
      users: users.slice(0, 10)
    };
    
    return createResponse(searchResult);
  }
};

// 文件上传API
export const uploadApi = {
  // 上传图片
  async uploadImage(file: File) {
    await delay(1000); // 模拟上传时间
    // 模拟返回图片URL
    const imageUrl = `https://picsum.photos/400/300?random=${Date.now()}`;
    return createResponse({ url: imageUrl }, '上传成功');
  },

  // 上传视频
  async uploadVideo(file: File) {
    await delay(3000); // 模拟视频上传时间
    // 模拟返回视频URL
    const videoUrl = `https://sample-videos.com/zip/10/mp4/SampleVideo_${Date.now()}.mp4`;
    return createResponse({ url: videoUrl }, '上传成功');
  }
};